//
//  UIButton+Countdown.swift
//  chat
//
//  Created by Meak Tsui on 2018/11/1.
//  Copyright © 2018 Meak Tsui. All rights reserved.
//

import Foundation
import UIKit

var kCountingDown = "contingDown"

extension UIButton {
    
    var countingDown:Bool {
        get {
            if let aValue = objc_getAssociatedObject(self, &kCountingDown) as? Bool {
                return aValue
            } else {
                return false
            }
        }
        set {
            objc_setAssociatedObject(self, &kCountingDown, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    /// 添加一个倒计时，便于实现类似短信验证码按钮的功能
    ///
    /// - Parameters:
    ///   - time: 倒计时时长
    ///   - tick: 每次步进时长
    ///   - onTick: 步进触发事件
    ///   - onFinish: 倒计时完成触发
    public func startCountDown(time:TimeInterval,tick:TimeInterval,onTick:((_ timer:Timer,_ times:Int,_ remain:TimeInterval) -> Void)? ,onFinish: ((_ times:Int) -> Void)? ) {
        var tickTimes = 0 //当前第几次触发
        countingDown = true
        _ = Timer.scheduledTimer(withTimeInterval: tick, repeats: true) { [weak self] timer in
            tickTimes += 1
            let spendTime = tick * TimeInterval(tickTimes)
            if spendTime >= time {
                timer.invalidate()
                self?.countingDown = false
                onFinish?(tickTimes)
            } else {
                onTick?(timer,tickTimes,time - spendTime)
            }
        }
    }
    
    public func isCountDown() -> Bool {
        return countingDown
    }
}
